package cn.jbq.videocaijian;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;


import com.jaygoo.widget.RangeSeekBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Button btnSelectVideo;
    private RangeSeekBar rangeSeekBar;
    private VideoView mVideoView;
    private Button BtnCut;
    private TextView tvOutPath;
    private VideoView mOutVideo;
    private Button btnMegre;
    private VideoView mMegreVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission(this);
        initView();
    }

    public static boolean checkPermission(
            Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && activity.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            activity.requestPermissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);

        }
        return false;
    }

    private void getVideoInfonation(){

    }

    private void initView() {
        btnSelectVideo = findViewById(R.id.btnGetVideo);
        btnSelectVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("video/*");
                if (Build.VERSION.SDK_INT < 19) {
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                } else {
                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                }
                startActivityForResult(intent, 1);
            }
        });

        mVideoView = findViewById(R.id.videoPlay);
        rangeSeekBar = findViewById(R.id.rangeSeekBar);
        BtnCut = findViewById(R.id.btnCaijJian);

        tvOutPath = findViewById(R.id.outPath);
        mOutVideo = findViewById(R.id.videoOut);

        BtnCut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cutVideo();
            }
        });

        btnMegre = findViewById(R.id.btnMegre);
        mMegreVideo = findViewById(R.id.videoMegre);
        btnMegre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mergeVideos();
            }
        });
    }

    private String srcPath;
    private String outPath;
    long startTime = 0L;
    long endTime = 0L;

    private String outPath2;


    private void mergeVideos() {
        try {
            File cacheDir = Environment.getExternalStorageDirectory();
            long systemTime = System.currentTimeMillis();
            final File videoFile = new File(cacheDir, "out_pinjie"+systemTime+".mp4");
            if (!videoFile.exists()) {
                videoFile.createNewFile();
                outPath2 = videoFile.getAbsolutePath();
            } else {
                outPath2 = videoFile.getAbsolutePath();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取两个Video的路径

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    Log.i("mergeVideos","开始时间"+System.currentTimeMillis()/1000+"");

                    copyAssetAndWrite("kaluode.mp4");
                    List<String> urls = new ArrayList<>();
                    String endVido = new File(getCacheDir(), "kaluode.mp4").getAbsolutePath();
                    urls.add(srcPath);
                    urls.add(endVido);

                    Log.i("mergeVideos", srcPath);
                    Log.i("mergeVideos", endVido);

                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    retriever.setDataSource(srcPath);
                    String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); //宽
                    String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); //高
                    String rotation = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);//视频的方向角度
                    long duration = Long.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) * 1000;//视频的长度

                    Log.i("mergeVideos", width);
                    Log.i("mergeVideos", height);


//                    VideoCompose videoCompose = new VideoCompose();
//                    videoCompose.composerVideo((ArrayList<String>) urls,outPath2);
//                    videoCompose.joinVideo();
//                    AWMp4ParserHelper.appendMp4List2(urls, outPath2);

                    copyAssetAndWrite("wujiaoxing_youse.png");
                    String waterIcon = new File(getCacheDir(), "wujiaoxing_youse.png").getAbsolutePath();

                    ArrayList<EpVideo> epVideos = new ArrayList<>();
                    EpVideo epVideo = new EpVideo(srcPath);
//                    epVideo.addDraw(new EpDraw(waterIcon,50,50,100,100,false));
                    epVideos.add(epVideo);//视频1
                    epVideos.add(new EpVideo(endVido));//视频2
//输出选项，参数为输出文件路径(目前仅支持mp4格式输出)
                    EpEditor.OutputOption outputOption = new EpEditor.OutputOption(outPath2);
                    outputOption.setHeight(Integer.parseInt(height));//输出视频高度,默认360
                    outputOption.setWidth(Integer.parseInt(width));//输出视频宽，默认480
                    outputOption.frameRate = 30;//输出视频帧率,默认30
                    outputOption.bitRate = 10;//输出视频码率,默认10
                    EpEditor.merge(epVideos, outputOption, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    Log.i("mergeVideos","结束时间"+System.currentTimeMillis()/1000+"");
                                    Log.i("mergeVideos", outPath2);
                                    showMegreResult();
                                    Toast.makeText(MainActivity.this, "合并成功", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onFailure() {

                        }

                        @Override
                        public void onProgress(float progress) {

                        }
                    });



                } catch (Exception e) {
                    e.printStackTrace();
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
//                            mMegreVideo.setVideoPath(endVido);
//                            mMegreVideo.start();
                            Toast.makeText(MainActivity.this, "合并失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }


            }
        }).start();
    }

    /**
     * 将asset文件写入缓存
     */
    private boolean copyAssetAndWrite(String fileName) {
        try {
            File cacheDir = getCacheDir();
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }
            File outFile = new File(cacheDir, fileName);
            if (!outFile.exists()) {
                boolean res = outFile.createNewFile();
                if (!res) {
                    return false;
                }
            } else {
                if (outFile.length() > 10) {//表示已经写入一次
                    return true;
                }
            }
            InputStream is = getAssets().open(fileName);
            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    private void showMegreResult() {
        mVideoView.pause();
        mOutVideo.pause();
        mMegreVideo.setVideoPath(outPath2);
        mMegreVideo.start();
    }

    private void cutVideo() {

        startTime = (long) (rangeSeekBar.getCurrentRange()[0] * 1000);
        endTime = (long) (rangeSeekBar.getCurrentRange()[1] * 1000);

        if (endTime == 0L || endTime <= startTime) {
            Toast.makeText(this, "请调整要截取的长度", Toast.LENGTH_SHORT).show();
            return;
        }


        try {
            File cacheDir = Environment.getExternalStorageDirectory();
            final File videoFile = new File(cacheDir, "out_caijian.mp4");
            if (!videoFile.exists()) {
                videoFile.createNewFile();
                outPath = videoFile.getAbsolutePath();
            } else {
                outPath = videoFile.getAbsolutePath();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    VideoClipUtils.clip(srcPath, outPath, startTime, endTime);
                } catch (IOException e) {
                    e.printStackTrace();
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "裁剪失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "裁剪成功", Toast.LENGTH_SHORT).show();
                        showCutResult();
                    }
                });
            }
        }).start();
    }

    private void showCutResult() {
        tvOutPath.setText(outPath);
        mVideoView.pause();
        mOutVideo.setVideoPath(outPath);
        mOutVideo.start();
    }

    long duration = 0L;
    Runnable runnable;

    private void startPlay(String path) {
        mVideoView.setVideoPath(path);

        mVideoView.start();
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                duration = mp.getDuration() / 1000;
                mp.setLooping(true);
                rangeSeekBar.setRange(0, duration);
                rangeSeekBar.setValue(0, duration);
                rangeSeekBar.setEnabled(true);
                rangeSeekBar.requestLayout();
                rangeSeekBar.setOnRangeChangedListener(new RangeSeekBar.OnRangeChangedListener() {
                    @Override
                    public void onRangeChanged(RangeSeekBar view, float min, float max, boolean isFromUser) {
                        mVideoView.seekTo((int) min * 1000);
                    }
                });
                final Handler handler = new Handler();
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        if (mVideoView.getCurrentPosition() >= rangeSeekBar.getCurrentRange()[1] * 1000) {
                            mVideoView.seekTo((int) rangeSeekBar.getCurrentRange()[0] * 1000);
                        }
                        handler.postDelayed(runnable, 1000);
                    }
                };
                handler.postDelayed(runnable, 1000);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            srcPath = UriPathUtils.getRealPathFromUri(this, data.getData());
            Log.i("getVideo", srcPath);
            startPlay(srcPath);
        }
    }
}